package com.magima.utils.image;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.magima.utils.CommonUtil;
import com.magima.utils.Constants;
import com.magima.utils.Logger;

public class GetImgFromUrl {
	public static final int COMPOUND_POSITION_LEFT = 0;
	public static final int COMPOUND_POSITION_TOP = 1;
	public static final int COMPOUND_POSITION_RIGHT = 2;
	public static final int COMPOUND_POSITION_BOTTOM = 3;
	
	private static final String IMG_DOWNLOAD_COUNT = "图片下载数";
	private static final String IMG_DOWNLOAD_FLOW_VOLUME = "图片下载流量";
	private static final String IMG_THREAD_POOL_QUEUE_LENGTH = "取图片排队数";
	
	private static final int IMAGE_MSG = 1;
	private static final int IMAGE_FETCH_ERROR = 2;
	
	private static int total_download_count = 0;
	private static long total_download_size = 0;
	private final static LinkedBlockingQueue<Runnable> imageFetcherQueue = new LinkedBlockingQueue<Runnable>(120);
	private final static LinkedBlockingQueue<Runnable> imageDecoderQueue = new LinkedBlockingQueue<Runnable>(50);
	private final static ExecutorService imageFetcherPool = new ThreadPoolExecutor(
			1, 6, 10, TimeUnit.SECONDS, imageFetcherQueue );
	
	private final static ExecutorService imageDecoderPool = new ThreadPoolExecutor(
			1, 3, 5000, TimeUnit.MILLISECONDS, imageDecoderQueue );

	private static HashMap<String, String> globalHeader = null;
	public static void setGlobalHeader(HashMap<String, String> header){
		globalHeader = header;
	}
	
	private static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
	private static HashMap<String, SoftReference<Drawable>> drawableCache = new HashMap<String, SoftReference<Drawable>>();

	private static Logger logger = new Logger() {
		@Override
		public void i(String tag, String string) {
			Log.i(tag, string);
		}
	};
	public static void setGlobalLogger(Logger log){
		logger = log;
	}
	
	public static File saveUrlFile(String url, String filePath) throws IOException {
		return saveUrlFile(url, filePath, null);
	}
	public static File saveUrlFile(String url, String filePath, DownloadFileProgressListener listener) throws IOException {
		File file = null;

		URL myFileUrl = new URL(url);     
		HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();     
		conn.setDoInput(true);     
        conn.setConnectTimeout(1500);
        conn.setReadTimeout(1500);
		if(globalHeader != null){
			@SuppressWarnings("rawtypes")
			Iterator iter = globalHeader.entrySet().iterator();
			while (iter.hasNext()) {
				@SuppressWarnings("rawtypes")
				Map.Entry entry = (Map.Entry) iter.next();
				String key = (String) entry.getKey();
				String val = (String) entry.getValue();
				conn.addRequestProperty(key,val);
			}
		}
		conn.connect();     

		InputStream inputStream = conn.getInputStream();  
		file = new File(filePath);  
		FileOutputStream fileOutput = new FileOutputStream(file);
		int totalSize = conn.getContentLength();
		int downloadedSize = 0;
        //create a buffer...
        byte[] buffer = new byte[1024];
        int bufferLength = 0; //used to store a temporary size of the buffer
        if ( totalSize == -1 ) {
        	if ( listener != null)
        		listener.onProgress(-1);
        }
		while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
            //add the data in the buffer to the file in the file output stream (the file on the sd card
            fileOutput.write(buffer, 0, bufferLength);
            //add up the size so we know how much is downloaded
            downloadedSize += bufferLength;
            //this is where you would do something to report the prgress, like this maybe
            if ( totalSize != -1 ) {
            	if ( listener != null)
            		listener.onProgress(downloadedSize*100/totalSize);
            }
        }
        //close the output stream when done
        fileOutput.close();
        inputStream.close();
		return file;
	}
	
	public interface GetFileCallback{
		void onGetFile(File file);
		void onBeforeFetchFile();
		void onError(Exception e);
	}

	public interface DownloadFileProgressListener{
		void onProgress(int progress);
	}

	private static HashMap<String, List<GetFileCallback>> waitingDownloadQueuePool = new HashMap<String, List<GetFileCallback>>();
	
	private static HashMap<String, List<View>> waitingDecodeQueuePool = new HashMap<String, List<View>>();
	
	public static void getCachedFile(final String url, GetFileCallback callback){
		getCachedFile(url,callback,null);
	}
	public static void getCachedFile(final String url, GetFileCallback callback, final DownloadFileProgressListener listener){
		if(url == null)
			return;
		
		String file_name1 = url.substring(url.lastIndexOf('/') + 1);
		final String file_name = CommonUtil.getImageUrlWithHashCodeSurFix(file_name1);
		
		File file = new File(Constants.IMAGE_CACHE_DIR + file_name);
		if(file.exists()){
			if ( callback != null ){
				callback.onGetFile(file);
			}
		} else {
			if ( callback != null ){
				callback.onBeforeFetchFile();
			}
			List<GetFileCallback> queue;
			synchronized ( waitingDownloadQueuePool ) {
				queue = waitingDownloadQueuePool.get(file_name);
				if ( queue != null ){
					queue.add(callback);
					return;
				} else {
					queue = new ArrayList<GetFileCallback>();
					waitingDownloadQueuePool.put(file_name, queue);
					queue.add(callback);
				}
			}
			final Handler handler = new Handler(){
				public void handleMessage(Message msg){
					List<GetFileCallback> q;
					synchronized ( waitingDownloadQueuePool ) {
						q = waitingDownloadQueuePool.get(file_name);
						waitingDownloadQueuePool.remove(file_name);
					}
					if ( q != null ) {
						for ( GetFileCallback callback : q ){
							if ( msg.what == IMAGE_MSG ) {							
								if ( callback != null ){
									callback.onGetFile((File) msg.obj);
								}
							} else if ( msg.what == IMAGE_FETCH_ERROR) {
								if ( callback != null ){
									callback.onError((Exception) msg.obj);
								}
							}
						}
					}					
				}
			};
			
			logger.i(IMG_THREAD_POOL_QUEUE_LENGTH, String.valueOf(imageFetcherQueue.size()));
			imageFetcherPool.execute(new Runnable(){
				@Override
				public void run() {
					String filePath = Constants.IMAGE_CACHE_DIR + file_name + ".part";
					try {
						File imgFile = saveUrlFile(url, filePath, listener);
						imgFile.renameTo(new File(Constants.IMAGE_CACHE_DIR + file_name));
						Message msg = new Message();
						msg.what = IMAGE_MSG;
						msg.obj = new File(Constants.IMAGE_CACHE_DIR + file_name);
						handler.sendMessage(msg);
						total_download_size += imgFile.length();
					} catch (IOException e) {
						File file = new File(filePath);
						if ( file.exists() )
							file.delete();
						Message msg = new Message();
						msg.what = IMAGE_FETCH_ERROR;
						msg.obj = e;
						handler.sendMessage(msg);							
					}

					logger.i(IMG_DOWNLOAD_FLOW_VOLUME, String.valueOf(total_download_size));
					logger.i(IMG_DOWNLOAD_COUNT, String.valueOf(++total_download_count));
					logger.i(IMG_THREAD_POOL_QUEUE_LENGTH, String.valueOf(imageFetcherQueue.size()));
				}							
			});
			
		}
	}
	
	public static Bitmap getBitmapFromUrl(String url) {
		if(url == null || url.equals("") || url.equals("null"))
			return null;

		if(imageCache.containsKey(url)){
			SoftReference<Bitmap> softReference = imageCache.get(url);  
			Bitmap bm = softReference.get();  
			if (bm != null) {
				return bm;
			}
		}
		return null;
	}
	
	public static void setImageResource(Resources resources, int resId, ImageView img){
		setImageResource(resources, resId, img, false);
	}
	
	public static void setImageResource(Resources resources, int resId, ImageView img, boolean needCorners){
		if ( needCorners ) {
			SoftReference<Bitmap> bitmapRef = imageCache.get(String.valueOf(resId));
			if ( bitmapRef != null && bitmapRef.get() != null ) {
				img.setTag(globalImageTagResId, null);
				img.setImageBitmap(bitmapRef.get());
			} else {
				decodeRoundedImageResource(resources, resId, img);
			}
		} else {
			img.setTag(globalImageTagResId, null);
			img.setImageResource(resId);
		}
	}
	
	private static Drawable getCachedDrawable(Resources resources, String url){
		SoftReference<Bitmap> bitmapRef = imageCache.get(url);
		if ( bitmapRef != null && bitmapRef.get() != null ) {
			SoftReference<Drawable> drawableRef = drawableCache.get(url);
			if ( drawableRef != null && drawableRef.get() != null )
				return drawableRef.get();
			else {
				Drawable drawable = new BitmapDrawable(resources, bitmapRef.get());
				drawableCache.put(url, new SoftReference<Drawable>(drawable));
				return drawable;
			}
		}
		return null;
	}
	
	private static void setCompoundDrawable(View view,Drawable drawable, int position, int width, int height){
		drawable.setBounds(0, 0, width, height);
		if ( view instanceof TextView ) {
			Drawable[] draws = ((TextView)view).getCompoundDrawables();
			draws[position] = drawable;
			((TextView)view).setCompoundDrawables(draws[COMPOUND_POSITION_LEFT],
					draws[COMPOUND_POSITION_TOP], 
					draws[COMPOUND_POSITION_RIGHT],
					draws[COMPOUND_POSITION_BOTTOM]);
		} else if ( view instanceof Button ) {
			Drawable[] draws = ((Button)view).getCompoundDrawables();
			draws[position] = drawable;
			((Button)view).setCompoundDrawables(draws[COMPOUND_POSITION_LEFT],
					draws[COMPOUND_POSITION_TOP], 
					draws[COMPOUND_POSITION_RIGHT],
					draws[COMPOUND_POSITION_BOTTOM]);
		}
	}
	
	public static void setCompoundImageResource(Resources resources, int resId, View view, int position, int width, int height, boolean needCorners){
		if ( position > COMPOUND_POSITION_BOTTOM || position < COMPOUND_POSITION_LEFT )
			return;
		if ( !(view instanceof TextView || view instanceof Button) )
			return;
		if ( needCorners ) {
			Drawable drawable = getCachedDrawable(resources,String.valueOf(resId));
			if ( drawable != null ) {
				view.setTag(globalImageTagResId, null);
				setCompoundDrawable(view, drawable, position, width, height);
			} else {
				view.setTag(globalWidthTagResId, width);
				view.setTag(globalHeightTagResId, height);
				view.setTag(globalPositionTagResId, position);
				decodeRoundedImageResource(resources, resId, view);
			}
		} else {
			view.setTag(globalImageTagResId, null);
			Drawable drawable = resources.getDrawable(resId);
			setCompoundDrawable(view, drawable, position, width, height);
		}
	}
	
	public static void setImageBackgroundResource(Resources resources, int resId, View view, boolean needCorners){
		if ( needCorners ) {
			Drawable drawable = getCachedDrawable(resources, String.valueOf(resId));
			if ( drawable != null ) {
				view.setTag(globalImageTagResId, null);
				view.setBackgroundDrawable(drawable);
			} else {
				decodeRoundedImageResource(resources, resId, view);
			}
		} else {
			view.setTag(globalImageTagResId, null);
			view.setBackgroundResource(resId);
		}
	}
	
	static private class BitmapDecodeResult {
		public Bitmap bitmap;
		public String id;
	}
	static final Handler imageHandler = new Handler(){
		public void handleMessage(Message msg){
			BitmapDecodeResult result = (BitmapDecodeResult)msg.obj;
			if ( result.bitmap != null ) {
				List<View> q;
				synchronized ( waitingDecodeQueuePool ) {
					q = waitingDecodeQueuePool.get(result.id);
					waitingDecodeQueuePool.remove(result.id);
				}
				if ( q != null ) {
					synchronized( q ) {
						for ( View view : q ){
							if ( view != null ){
								String loading_img_url = (String)view.getTag(globalImageTagResId);
								if ( loading_img_url != null && loading_img_url.equals(result.id) ){
									if ( view instanceof ImageView )
										((ImageView) view).setImageBitmap(result.bitmap);
									else if ( view instanceof TextView || view instanceof Button ){
										int width = (Integer) view.getTag(globalWidthTagResId);
										int height = (Integer) view.getTag(globalHeightTagResId);
										int position = (Integer) view.getTag(globalPositionTagResId);
										Drawable drawable = new BitmapDrawable(result.bitmap);
										drawableCache.put(loading_img_url,new SoftReference<Drawable>(drawable));
										setCompoundDrawable(view, drawable, position, width, height);
									} else {
										Drawable drawable = new BitmapDrawable(result.bitmap);
										drawableCache.put(loading_img_url,new SoftReference<Drawable>(drawable));
										view.setBackgroundDrawable(drawable);
									}
								}
							}
						}
					}
				}				
			}			
			result = null;
		}
	};
	private static void decodeRoundedImageResource(final Resources resources, final int resId, View img){
		img.setTag(globalImageTagResId, String.valueOf(resId));
		List<View> queue;
		synchronized ( waitingDecodeQueuePool ) {
			queue = waitingDecodeQueuePool.get(String.valueOf(resId));
			if ( queue != null ){
				queue.add(img);
				return;
			} else {
				queue = new ArrayList<View>();
				queue.add(img);
				waitingDecodeQueuePool.put(String.valueOf(resId), queue);
			}
		}
		imageDecoderPool.execute(new Runnable(){
			@Override
			public void run() {
				Bitmap rounded = null;
				try {
					Bitmap bm = BitmapFactory.decodeResource(resources, resId);
					rounded = ImageUtil.getRoundedCornerBitmap(bm);
					imageCache.put(String.valueOf(resId), new SoftReference<Bitmap>(rounded));
					bm.recycle();
					bm = null;
				} finally {						
					Message msg = new Message();
					BitmapDecodeResult result = new BitmapDecodeResult();
					result.id = String.valueOf(resId);
					result.bitmap = rounded;
					msg.obj = result;
					imageHandler.sendMessage(msg);
				}
			}							
		});
		
	}
	private static void decodeFileImage(final String url, final File file, View img, final boolean needCorners ){
		List<View> queue;
		synchronized ( waitingDecodeQueuePool ) {
			queue = waitingDecodeQueuePool.get(url);
			if ( queue != null ){
				queue.add(img);
				return;
			} else {
				queue = new ArrayList<View>();
				queue.add(img);
				waitingDecodeQueuePool.put(url, queue);
			}
		}
		int w = img.getWidth();
		int h = img.getHeight();
		if ( w == 0 )
			w = img.getContext().getResources().getDisplayMetrics().widthPixels;
		if ( h == 0 )
			h = img.getContext().getResources().getDisplayMetrics().heightPixels;
		final int _w = w;
		final int _h = h;
		
		imageDecoderPool.execute(new Runnable(){
			@Override
			public void run() {
				Bitmap bm = null;
				try {
					bm = shrinkBitmap(file,_w, _h);//BitmapFactory.decodeFile(file.getPath());
					if ( bm != null ) {
						if(needCorners) {
							Bitmap oldBitmap = bm;
							bm = ImageUtil.getRoundedCornerBitmap(bm);
							oldBitmap.recycle();
							oldBitmap = null;
						}
						imageCache.put(url, new SoftReference<Bitmap>(bm));
					}
				} finally {
					Message msg = new Message();
					BitmapDecodeResult result = new BitmapDecodeResult();
					result.id = url;
					result.bitmap = bm;
					msg.obj = result;
					imageHandler.sendMessage(msg);
				}
			}							
		});
	}

	public static void setImageUrl(String url, ImageView img){
		setImageUrl(url, img, false);
	}
	
	public static void setImageUrl(String url, ImageView img, boolean needCorners){
        setImageUrl(url, img, 0, needCorners);
	}

    public static void setImageUrl(final String url, final ImageView img, int default_rId, final boolean needCorners){
        if(default_rId > 0){
            img.setImageResource(default_rId);
        }

        if(url == null || url.equals("") || url.equals("null"))
            return;

        SoftReference<Bitmap> softReference = imageCache.get(url);
        if(softReference!=null && softReference.get()!=null){
            img.setTag(globalImageTagResId, null);
            img.setImageBitmap(softReference.get());
        }else{
            getDrawableNoSoftReference(url, img, needCorners);
        }
    }

	public static void setCompoundImageUrl(Resources resources, String url, View view, int position, int width, int height, boolean needCorners){
		if(url == null || url.equals("") || url.equals("null"))
			return;
		if ( position > COMPOUND_POSITION_BOTTOM || position < COMPOUND_POSITION_LEFT )
			return;
		if ( !(view instanceof TextView || view instanceof Button) )
			return;
		
		Drawable drawable = getCachedDrawable(resources, url);
		if (drawable != null) {
			view.setTag(globalImageTagResId, null);
			setCompoundDrawable(view, drawable, position, width, height);
		}else{
			view.setTag(globalWidthTagResId, width);
			view.setTag(globalHeightTagResId, height);
			view.setTag(globalPositionTagResId, position);
			getDrawableNoSoftReference(url, view, needCorners);
		}
	}
	
	private static void getDrawableNoSoftReference(final String url, View img, final boolean needCorners){
		img.setTag(globalImageTagResId, url);
		class MyGetFileCallback implements GetFileCallback{
			private View img;
			public MyGetFileCallback(View img){
				this.img = img;
			}
			@Override
			public void onGetFile(File file) {
				decodeFileImage(url, file, img ,needCorners);
			}
			@Override
			public void onBeforeFetchFile() {
			}
			@Override
			public void onError(Exception e) {
			}
		}
		getCachedFile(url, new MyGetFileCallback(img));
	}
	
	private static int globalImageTagResId = 0;
	private static int globalWidthTagResId = 0;
	private static int globalHeightTagResId = 0;
	private static int globalPositionTagResId = 0;
	
	private static OnImageClickListener globalOnClickImageListener = null;
	public interface OnImageClickListener{
		void onClick(View v, Context context, String url, String thumbnail_url, boolean canScreenShot);
		void onClick(View v, Context context, ArrayList<String> thumbnail_urls, ArrayList<String> origin_urls, int index, boolean canScreenShot);
	}
	public static void setGlobalOnClickImageListener(OnImageClickListener listener){
		globalOnClickImageListener = listener;
	}
	
	public static void setGlobalImageUrlTagResId(int resId ) {
		globalImageTagResId = resId;
	}
	
	public static void setGlobalImageTagsResIdForCompoundDrawable(int widthResId, int heightResId, int positionResId ){
		globalWidthTagResId = widthResId;
		globalHeightTagResId = heightResId;
		globalPositionTagResId = positionResId;
	}
	
	public static void clickEnlarge(final ArrayList<String> thumbnail_urls, final ArrayList<String> origin_urls, 
			ImageView img, final int index, final Context context, final boolean canScreenShot){
		if ( globalOnClickImageListener != null ){
			img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					globalOnClickImageListener.onClick(v, context, thumbnail_urls, origin_urls, index, canScreenShot);
				}
			});
		}
	}
	
	public static void clickEnlarge(final String url, final String thumbnail_url, 
			final ImageView img, final Context context, final boolean canScreenShot){
		if ( globalOnClickImageListener != null ){
			img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					globalOnClickImageListener.onClick(v, context, url, thumbnail_url, canScreenShot);
                    ArrayList<String> thumbnail_urls = new ArrayList<String>();
                    thumbnail_urls.add(thumbnail_url);
                    ArrayList<String> origin_urls = new ArrayList<String>();
                    origin_urls.add(url);
                    globalOnClickImageListener.onClick(v, context, thumbnail_urls, origin_urls, 0, canScreenShot);
				}
			});
		}
	}

    public static void clickToPreview(final String url, final String thumbnail_url,
                                      final Context context, final boolean canScreenShot){
        globalOnClickImageListener.onClick(null, context, url, thumbnail_url, canScreenShot);
    }
	
	public static void clickEnlarge(final ArrayList<String> thumbnail_urls, final ArrayList<String> origin_urls, ImageView img, final int index, final Context context){
		clickEnlarge(thumbnail_urls, origin_urls, img, index, context, true);
	}
	
	public static void clickEnlarge(final String url, final String thumbnail_url, final ImageView img, final Context context){
		clickEnlarge(url, thumbnail_url, img, context, true);
	}

    public static void clickEnlarge(final String url, final String thumbnail_url, final ImageView img, final Context context,int flag){
        if(globalOnClickImageListener != null){
            ArrayList<String> thumbnail_urls = new ArrayList<String>();
            thumbnail_urls.add(thumbnail_url);
            ArrayList<String> origin_urls = new ArrayList<String>();
            origin_urls.add(url);
            globalOnClickImageListener.onClick(img, context, thumbnail_urls, origin_urls, 0, true);
        }
    }
	
	public static File saveFile(Bitmap bm, String filePath, String fileName, int quality) throws IOException {  
        File imgFile = new File(filePath + fileName);  
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imgFile));  
        bm.compress(Bitmap.CompressFormat.JPEG, quality, bos);  
        bos.flush();  
        bos.close();  
        
        return imgFile;
    }
	
	public static File saveFile(Bitmap bm, String filePath, String fileName) throws IOException {  
        return saveFile(bm,filePath, fileName, 100);
    }
	
	public static Bitmap shrinkBitmap(String path, int dstWidth, int dstHeight) {
		return shrinkBitmap(new File(path), dstWidth, dstHeight);
	}
	
	public static Bitmap shrinkBitmap(File file, int dstWidth, int dstHeight) {
		Bitmap resizedBitmap = null;
		try {
			int inWidth = 0;
			int inHeight = 0;
			InputStream in = new FileInputStream(file);

			// decode image size (decode metadata only, not the whole image)
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(in, null, options);
			in.close();
			in = null;

			// save width and height
			inWidth = options.outWidth;
			inHeight = options.outHeight;

			// decode full image pre-resized
			in = new FileInputStream(file);
			options = new BitmapFactory.Options();
			// calc rought re-size (this is no exact resize)
			if ( inWidth > inHeight )
				options.inSampleSize = Math.max(1,
						Math.max(inWidth / dstWidth, inHeight / dstHeight));
			else
				options.inSampleSize = Math.max(1,
						Math.max(inHeight / dstWidth, inWidth / dstHeight));
			if ( options.inSampleSize == 1 ) {
				return BitmapFactory.decodeStream(in);
			}
			// decode full image
			Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
			in.close();
			if ( roughBitmap == null )
				return null;
			
			// calc exact destination size
			Matrix m = new Matrix();
			RectF inRect = new RectF(0, 0, roughBitmap.getWidth(),
					roughBitmap.getHeight());
			RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
			m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
			float[] values = new float[9];
			m.getValues(values);

			// resize bitmap
			resizedBitmap = Bitmap.createScaledBitmap(roughBitmap,
					(int) (roughBitmap.getWidth() * values[0]),
					(int) (roughBitmap.getHeight() * values[4]), true);
			if ( roughBitmap != resizedBitmap) //not same bitmap
				roughBitmap.recycle();
		} catch (IOException e) {
			return null;
		}
		return resizedBitmap;
	}
	
	public static File shrinkFile(File file, String outputFileName, int dstWidth, int dstHeight, int quality){
		Bitmap resizedBitmap = shrinkBitmap(file, dstWidth, dstHeight);

		// save image
		try
		{
			File outFile = new File(outputFileName);
		    FileOutputStream out = new FileOutputStream(outFile);
		    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
		    out.close();
		    return outFile;
		}
		catch (Exception e)
		{
		    Log.e("Image", e.getMessage(), e);
		}
		return null;
	}
	
	public static Bitmap shrinkAndRotateFile(File file, int dstWidth, int dstHeight) {
		Bitmap resizedBitmap;
		int rotate = ImageUtil.getImageOrientation(file);
		if ( rotate != 0 ) {
			Bitmap shiriked = GetImgFromUrl.shrinkBitmap(file, dstWidth, dstHeight);
			resizedBitmap = ImageUtil.rotateBitmap(shiriked, rotate);
			shiriked.recycle();
		} else
			resizedBitmap = shrinkBitmap(file, dstWidth, dstHeight);
		return resizedBitmap;
	}
	
	public static File shrinkAndRotateFile(File file, String outputFileName, int dstWidth, int dstHeight, int quality){
		Bitmap resizedBitmap = shrinkAndRotateFile(file, dstWidth, dstHeight);
		if ( resizedBitmap == null ) //解析图片出错，可能不是图片文件用了图片文件的后缀
			return null;
		// save image
		try
		{
			File outFile = new File(outputFileName);
		    FileOutputStream out = new FileOutputStream(outFile);
		    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out);
		    out.close();
		    resizedBitmap.recycle();
		    return outFile;
		}
		catch (Exception e)
		{
		    Log.e("Image", e.getMessage(), e);
		}
		return null;
	}
}
